<template>
	<view class="comment_item">
		<view class="comment_content_wrap">
			<navigator url="/pages/myinfo/myinfo?user_id={{comment.user_id}}">
				<image
					class="user_avatar"
					:src="comment.avatar_url"
					mode="aspectFill"
					lazy-load="true"
				/>
			</navigator>
			<view v-if="comment.parent_id" class="username"
				>{{ comment.name }}回复{{ getParentUserName(comment.parent_id).name }}:
			</view>
			<view v-else class="username">{{ comment.name }}:</view>
		</view>
		<view class="content"
			>{{ comment.content }}
			<van-icon  class="comment" name="chat-o" @click="hanldeOpenComment(comment)"
		/>
		<van-icon v-if="comment.user_id === userId" class="comment" name="delete-o" @click="hanldeDeleteComment(comment.id)"/>
		</view>
	</view>

	<view class="comment-children">
		<RelyComment
			v-for="child in comment.children"
			:key="child.id"
			:comment="child"
			:allComments="allComments"
			:userId = "userId"
			@relyComment = "hanldeOpenComment(child)"
			@removeComment = "hanldeDeleteComment(child.id)"
		/>
	</view>

</template>

<script setup>
import RelyComment from './rely-comment.vue'
const { comment, allComments, userId } = defineProps({
	comment: {
		type: Object,
		required: true
	},
	allComments: {
		type: Array,
		required: true
	},
	userId: {
		required: true
	}
})
// 获取父亲的名字
function getParentUserName(parentId) {
	// 定义递归函数findParent
	const findParent = (comments, pid) => {
		for (const comment of comments) {
			if (comment.id === pid) {
				return comment
			}
			if (comment.children) {
				// 递归搜索子评论列表
				const found = findParent(comment.children, pid)
				if (found) return found
			}
		}
	}
	// 调用递归函数从根评论开始查找
	const parentComment = findParent(allComments, parentId)
	return parentComment ? parentComment : '未知'
}

// 回复评论
const emit = defineEmits(['relyComment','removeComment'])
function hanldeOpenComment(comment) {
	emit('relyComment',comment)
}

// 删除评论
function hanldeDeleteComment(commentId) {
	emit('removeComment', commentId)
}
</script>

<style lang="less" scoped>
.comment_item {
	padding-left: 25rpx;
	margin-bottom: 30rpx;

	.user_avatar {
		width: 70rpx;
		height: 70rpx;
		border-radius: 50%;
		margin-right: 20rpx;
	}

	.comment_content_wrap {
		display: flex;
		vertical-align: middle;
		align-items: center;
		.username {
			font-weight: 700;
			font-size: 28rpx;
			margin-bottom: 10rpx;
		}
	}
	.comment {
		margin-left: 20rpx;
	}
	.content {
		margin-top: 10rpx;
		margin-left: 80rpx;
		font-size: 27rpx;
		color: #444;
	}
}
</style>
